<!doctype html>



  


<html class="theme-next pisces use-motion" lang="zh-CN">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>






<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />



  <meta name="google-site-verification" content="ojuCmbEUKDUtduqtuqs4jjwa-kJTF2PAJM-YEfGBpaU" />







  <meta name="baidu-site-verification" content="Q2zf7SFGkD" />




  <meta name="360-site-verification" content="06fcdce1b9c04508be6260fe40d4fcd0" />




  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.0" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="go," />





  <link rel="alternate" href="/atom.xml" title="WillXue's Blog" type="application/atom+xml" />




  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.0" />






<meta property="og:type" content="article">
<meta property="og:title" content="go语言学习（一）net/http包客户端实例练习">
<meta property="og:url" content="http://willxue.top/blog/golang-learn-01-20161130/index.html">
<meta property="og:site_name" content="WillXue's Blog">
<meta property="og:image" content="http://willxue.ufile.ucloud.com.cn/golang1.png">
<meta property="og:updated_time" content="2016-12-01T11:21:46.298Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="go语言学习（一）net/http包客户端实例练习">
<meta name="twitter:image" content="http://willxue.ufile.ucloud.com.cn/golang1.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    sidebar: {"position":"left","display":"post","offset":12,"offset_float":0,"b2t":false,"scrollpercent":false},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://willxue.top/blog/golang-learn-01-20161130/"/>





  <title> go语言学习（一）net/http包客户端实例练习 | WillXue's Blog </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  





  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?0140105715a4b89c631d1e11b622c4ad";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>










  
  
    
  

  <div class="container sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">WillXue's Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">一个好高骛远的码农</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-commonweal">
          <a href="/404.html" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-heartbeat"></i> <br />
            
            公益404
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
    <link itemprop="mainEntityOfPage" href="http://willxue.top/blog/golang-learn-01-20161130/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="willxue">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="http://willxue.ufile.ucloud.com.cn/logo.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="WillXue's Blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                go语言学习（一）net/http包客户端实例练习
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2016-11-30T23:18:07+08:00">
                2016-11-30
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/go/" itemprop="url" rel="index">
                    <span itemprop="name">go</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
              <span class="post-meta-divider">|</span>
              <span class="post-meta-item-icon">
                <i class="fa fa-comment-o"></i>
              </span>
              
                <a href="/blog/golang-learn-01-20161130/#SOHUCS" itemprop="discussionUrl">
                  <span id="changyan_count_unit" class="post-comments-count hc-comment-count" data-xid="blog/golang-learn-01-20161130/" itemprop="commentsCount"></span>
                </a>
              
            
          

          
          
             <span id="/blog/golang-learn-01-20161130/" class="leancloud_visitors" data-flag-title="go语言学习（一）net/http包客户端实例练习">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数 </span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          

          

        </div>
      </header>
    

    <div class="post-body" itemprop="articleBody">

      
      

      
        <p><img src="http://willxue.ufile.ucloud.com.cn/golang1.png" alt="界面"></p>
<a id="more"></a>
<blockquote>
<p>因为我是学Java的，主要做web开发，所以看了点go的基础知识后，就试着把以前的demo用go实现以下，而且go web开发非常简便只要几行代码，就能实现简单http服务器，今天主要写一下用net/http包模拟客户端发送请求实现百度推送（实时）。</p>
</blockquote>
<h1 id="开始"><a href="#开始" class="headerlink" title="开始"></a>开始</h1><h2 id="项目结构"><a href="#项目结构" class="headerlink" title="项目结构"></a>项目结构</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line">.</div><div class="line">├── static</div><div class="line">|   ├── css</div><div class="line">|   └── layer</div><div class="line">├── views</div><div class="line">|   └── index.html</div><div class="line">└── main.go</div></pre></td></tr></table></figure>
<h2 id="main-go"><a href="#main-go" class="headerlink" title="main.go"></a>main.go</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div><div class="line">51</div><div class="line">52</div><div class="line">53</div><div class="line">54</div><div class="line">55</div><div class="line">56</div><div class="line">57</div><div class="line">58</div><div class="line">59</div><div class="line">60</div><div class="line">61</div><div class="line">62</div><div class="line">63</div><div class="line">64</div><div class="line">65</div><div class="line">66</div><div class="line">67</div><div class="line">68</div><div class="line">69</div><div class="line">70</div><div class="line">71</div><div class="line">72</div><div class="line">73</div><div class="line">74</div><div class="line">75</div><div class="line">76</div><div class="line">77</div><div class="line">78</div><div class="line">79</div><div class="line">80</div><div class="line">81</div><div class="line">82</div><div class="line">83</div><div class="line">84</div><div class="line">85</div><div class="line">86</div><div class="line">87</div><div class="line">88</div><div class="line">89</div><div class="line">90</div><div class="line">91</div><div class="line">92</div><div class="line">93</div><div class="line">94</div><div class="line">95</div><div class="line">96</div></pre></td><td class="code"><pre><div class="line">package main</div><div class="line"></div><div class="line">import (</div><div class="line">	&quot;fmt&quot;</div><div class="line">	&quot;html/template&quot;</div><div class="line">	&quot;io/ioutil&quot;</div><div class="line">	&quot;log&quot;</div><div class="line">	&quot;net/http&quot;</div><div class="line">	&quot;net/url&quot;</div><div class="line">	&quot;strings&quot;</div><div class="line">)</div><div class="line"></div><div class="line">func main() &#123;</div><div class="line">	http.HandleFunc(&quot;/&quot;, index)</div><div class="line">	http.HandleFunc(&quot;/send&quot;, bdSend)</div><div class="line">	//处理静态文件</div><div class="line">	http.Handle(&quot;/static/&quot;, http.StripPrefix(&quot;/static/&quot;, http.FileServer(http.Dir(&quot;static&quot;))))</div><div class="line">	err := http.ListenAndServe(&quot;:80&quot;, nil)</div><div class="line">	if err != nil &#123;</div><div class="line">		log.Fatal(err)</div><div class="line">	&#125;</div><div class="line">&#125;</div><div class="line"></div><div class="line">//首页</div><div class="line">func index(w http.ResponseWriter, r *http.Request) &#123;</div><div class="line">	if r.Method == &quot;GET&quot; &#123;</div><div class="line">		t, err := template.ParseFiles(&quot;views/index.html&quot;)</div><div class="line">		if err != nil &#123;</div><div class="line">			log.Fatal(err)</div><div class="line">		&#125;</div><div class="line">		t.Execute(w, nil)</div><div class="line">	&#125;</div><div class="line">&#125;</div><div class="line"></div><div class="line">//推送</div><div class="line">func bdSend(w http.ResponseWriter, r *http.Request) &#123;</div><div class="line">	if r.Method == &quot;POST&quot; &#123;</div><div class="line">		request(w, r)</div><div class="line">	&#125;</div><div class="line">&#125;</div><div class="line"></div><div class="line">//模拟http客户端post发送请求</div><div class="line">func request(w http.ResponseWriter, r *http.Request) &#123;</div><div class="line">	//先解析form</div><div class="line">	err := r.ParseForm()</div><div class="line">	</div><div class="line">	if err != nil &#123;</div><div class="line">		log.Fatal(err)</div><div class="line">	&#125;</div><div class="line">	//请求地址</div><div class="line">	var apiURL string</div><div class="line">	switch r.Form[&quot;oper&quot;][0] &#123;</div><div class="line">	case &quot;post&quot;:</div><div class="line">		apiURL = &quot;http://data.zz.baidu.com/urls&quot;</div><div class="line">	case &quot;update&quot;:</div><div class="line">		apiURL = &quot;http://data.zz.baidu.com/update&quot;</div><div class="line">	case &quot;del&quot;:</div><div class="line">		apiURL = &quot;http://data.zz.baidu.com/del&quot;</div><div class="line">	&#125;</div><div class="line"></div><div class="line">	//初始化参数</div><div class="line">	param := url.Values&#123;&#125;</div><div class="line"></div><div class="line">	//配置请求参数,方法内部已处理urlencode问题,中文参数可以直接传参</div><div class="line">	param.Set(&quot;site&quot;, r.Form[&quot;site&quot;][0])</div><div class="line">	param.Set(&quot;token&quot;, r.Form[&quot;token&quot;][0])</div><div class="line"></div><div class="line">	var URL *url.URL</div><div class="line">	URL, err = url.Parse(apiURL)</div><div class="line">	if err != nil &#123;</div><div class="line">		fmt.Printf(&quot;解析url错误:\r\n%v&quot;, err)</div><div class="line">	&#125;</div><div class="line">	//如果参数中有中文参数,这个方法会进行URLEncode</div><div class="line">	URL.RawQuery = param.Encode()</div><div class="line">	client := &amp;http.Client&#123;&#125;</div><div class="line">	req, _ := http.NewRequest(&quot;POST&quot;, URL.String(), strings.NewReader(r.Form[&quot;sendURL&quot;][0]))</div><div class="line"></div><div class="line">	req.Header.Set(&quot;Content-Type&quot;, &quot;application/x-www-form-urlencoded&quot;)</div><div class="line">	//req.Header.Set(&quot;User-Agent&quot;, &quot;curl/7.12.1&quot;)</div><div class="line">	//req.Header.Set(&quot;Host&quot;, &quot;data.zz.baidu.com&quot;)</div><div class="line"></div><div class="line">	//发送请求</div><div class="line">	resp, err := client.Do(req)</div><div class="line">	//注意关闭resp.Body</div><div class="line">	defer resp.Body.Close()</div><div class="line">	data, err := ioutil.ReadAll(resp.Body)</div><div class="line">	if err != nil &#123;</div><div class="line">		fmt.Printf(&quot;请求失败,错误信息:\r\n%v&quot;, err)</div><div class="line">	&#125; else &#123;</div><div class="line">		//var returns map[string]interface&#123;&#125;</div><div class="line">		//json.Unmarshal(data, &amp;returns)</div><div class="line">		//data, err = json.Marshal(returns)</div><div class="line">		//将返回的json数据返给客户端浏览器</div><div class="line">		fmt.Fprintln(w, string(data))</div><div class="line">	&#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h2 id="index-html"><a href="#index-html" class="headerlink" title="index.html"></a>index.html</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div><div class="line">51</div><div class="line">52</div><div class="line">53</div><div class="line">54</div><div class="line">55</div><div class="line">56</div><div class="line">57</div><div class="line">58</div><div class="line">59</div><div class="line">60</div><div class="line">61</div><div class="line">62</div><div class="line">63</div><div class="line">64</div><div class="line">65</div><div class="line">66</div><div class="line">67</div><div class="line">68</div><div class="line">69</div><div class="line">70</div><div class="line">71</div><div class="line">72</div><div class="line">73</div><div class="line">74</div><div class="line">75</div><div class="line">76</div><div class="line">77</div><div class="line">78</div><div class="line">79</div><div class="line">80</div><div class="line">81</div><div class="line">82</div></pre></td><td class="code"><pre><div class="line">&lt;!DOCTYPE html&gt;</div><div class="line">&lt;html lang=&quot;zh-CN&quot;&gt;</div><div class="line">	&lt;head&gt;</div><div class="line">		&lt;meta charset=&quot;utf-8&quot;&gt;</div><div class="line">		&lt;meta http-equiv=&quot;X-UA-Compatible&quot; content=&quot;IE=edge&quot;&gt;</div><div class="line">		&lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1&quot;&gt;</div><div class="line">		&lt;!-- 上述3个meta标签*必须*放在最前面，任何其他内容都*必须*跟随其后！ --&gt;</div><div class="line">		&lt;title&gt;百度主动推送(实时)&lt;/title&gt;</div><div class="line">		&lt;LINK rel=&quot;Bookmark&quot; href=&quot;/static/favicon.ico&quot;&gt;</div><div class="line">		&lt;LINK rel=&quot;Shortcut Icon&quot; href=&quot;/static/favicon.ico&quot; /&gt;</div><div class="line">		&lt;!-- Bootstrap --&gt;</div><div class="line">		&lt;link rel=&quot;stylesheet&quot; href=&quot;//cdn.bootcss.com/bootstrap/3.3.5/css/bootstrap.min.css&quot;&gt;</div><div class="line">		&lt;link rel=&quot;stylesheet&quot; href=&quot;/static/css/style.css&quot;&gt;</div><div class="line">		&lt;!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries --&gt;</div><div class="line">		&lt;!-- WARNING: Respond.js doesn&apos;t work if you view the page via file:// --&gt;</div><div class="line">		&lt;!--[if lt IE 9]&gt;</div><div class="line">			&lt;script src=&quot;//cdn.bootcss.com/html5shiv/3.7.2/html5shiv.min.js&quot;&gt;&lt;/script&gt;</div><div class="line">			&lt;script src=&quot;//cdn.bootcss.com/respond.js/1.4.2/respond.min.js&quot;&gt;&lt;/script&gt;</div><div class="line">	    &lt;![endif]--&gt;</div><div class="line">	&lt;/head&gt;</div><div class="line">	&lt;body class=&quot;bg-body&quot;&gt;</div><div class="line">		&lt;div class=&quot;container text-center bg&quot;&gt;</div><div class="line">			&lt;h1&gt;百度主动推送（实时）&lt;/h1&gt;</div><div class="line">			&lt;form class=&quot;form-horizontal&quot; id=&quot;form&quot; &gt;</div><div class="line">				&lt;div class=&quot;form-group  form-group-lg&quot;&gt;</div><div class="line">					&lt;div class=&quot;col-sm-8 col-sm-offset-2&quot;&gt;</div><div class="line">						&lt;select class=&quot;form-control&quot; id=&quot;oper&quot; name=&quot;oper&quot;&gt;</div><div class="line">							&lt;option value=&quot;post&quot;&gt;推送数据&lt;/option&gt;</div><div class="line">							&lt;option value=&quot;update&quot;&gt;更新数据&lt;/option&gt;</div><div class="line">							&lt;option value=&quot;del&quot;&gt;删除数据&lt;/option&gt;</div><div class="line">						&lt;/select&gt;</div><div class="line">					&lt;/div&gt;</div><div class="line">				&lt;/div&gt;</div><div class="line">				&lt;div class=&quot;form-group  form-group-lg&quot;&gt;</div><div class="line">					&lt;div class=&quot;col-sm-8 col-sm-offset-2&quot;&gt;</div><div class="line">						&lt;input type=&quot;tel&quot; class=&quot;form-control&quot; id=&quot;site&quot; name=&quot;site&quot; placeholder=&quot;要推送内容的网站，例如：www.example.com&quot; required &gt;</div><div class="line">					&lt;/div&gt;</div><div class="line">				&lt;/div&gt;</div><div class="line">				&lt;div class=&quot;form-group  form-group-lg&quot;&gt;</div><div class="line">					&lt;div class=&quot;col-sm-8 col-sm-offset-2&quot;&gt;</div><div class="line">						&lt;input type=&quot;tel&quot; class=&quot;form-control&quot; id=&quot;token&quot; name=&quot;token&quot; placeholder=&quot;百度站长平台秘钥，例如：ZD4V6EK2QNpzwill&quot; required &gt;</div><div class="line">					&lt;/div&gt;</div><div class="line">				&lt;/div&gt;</div><div class="line">				&lt;div class=&quot;form-group  form-group-lg&quot;&gt;</div><div class="line">					&lt;div class=&quot;col-sm-8 col-sm-offset-2&quot;&gt;</div><div class="line">						&lt;textarea class=&quot;form-control&quot; name=&quot;sendURL&quot; rows=&quot;8&quot; placeholder=&quot;网址之间要换行，例如：</div><div class="line">http://www.example/abc.hml</div><div class="line">http://www.example/bcd.html&quot; &gt;&lt;/textarea&gt;</div><div class="line">					&lt;/div&gt;</div><div class="line">				&lt;/div&gt;</div><div class="line">				&lt;div class=&quot;form-group  form-group-lg&quot;&gt;</div><div class="line">					&lt;div class=&quot;col-sm-8 col-sm-offset-2&quot;&gt;</div><div class="line">						&lt;button type=&quot;button&quot; class=&quot;btn btn-success btn-lg btn-block&quot; onclick=&quot;ajaxSub()&quot;&gt;推送&lt;/button&gt;</div><div class="line">					&lt;/div&gt;</div><div class="line">				&lt;/div&gt;</div><div class="line">				&lt;h3&gt;&amp;copy; 2016 powered by &lt;a href=&quot;http://willxue.top&quot; target=&quot;_blank&quot;&gt;willxue&lt;/a&gt;&lt;/h3&gt;</div><div class="line">			&lt;/form&gt;</div><div class="line">		</div><div class="line">			&lt;!-- jQuery (necessary for Bootstrap&apos;s JavaScript plugins) --&gt;</div><div class="line">			&lt;script src=&quot;//cdn.bootcss.com/jquery/1.11.3/jquery.min.js&quot;&gt;&lt;/script&gt;</div><div class="line">			&lt;!-- Include all compiled plugins (below), or include individual files as needed --&gt;</div><div class="line">			&lt;script src=&quot;//cdn.bootcss.com/bootstrap/3.3.5/js/bootstrap.min.js&quot;&gt;&lt;/script&gt;</div><div class="line">			&lt;script src=&quot;/static/layer/layer.js&quot;&gt;&lt;/script&gt;</div><div class="line">			&lt;script type=&quot;text/javascript&quot;&gt;</div><div class="line">				function ajaxSub()&#123;</div><div class="line">					$.post(&quot;/send&quot;, $(&quot;#form&quot;).serialize(), function(result)&#123;</div><div class="line">						if (result.indexOf(&quot;Exception&quot;)&gt;0) &#123;</div><div class="line">							layer.alert(&quot;请确认站点和token是否匹配&quot;,&#123;title: &quot;错误&quot;,icon:2&#125;);</div><div class="line">						&#125; else &#123;</div><div class="line">							var data = JSON.parse(result);</div><div class="line">							if (result.indexOf(&quot;success&quot;)&gt;0) &#123;</div><div class="line">								layer.alert(&quot;成功推送了：&quot;+data.success+&quot; 个&lt;br/&gt;今天还能推送：&quot;+data.remain+&quot; 个&lt;br/&gt;不是本站而未处理的url列表： &quot;+data.not_same_site+&quot;&lt;br/&gt;不合法的url：&quot;+data.not_valid,&#123;icon:1&#125;);</div><div class="line">							&#125; else&#123;</div><div class="line">								layer.alert(&quot;推送失败了，错误码：&quot;+data.error+&quot;&lt;br/&gt;错误描述：&quot;+data.message,&#123;title: &quot;错误&quot;,icon:2&#125;);</div><div class="line">							&#125;</div><div class="line">						&#125;</div><div class="line">					&#125;);</div><div class="line">				&#125;</div><div class="line">			&lt;/script&gt;</div><div class="line">		&lt;/div&gt;</div><div class="line">	&lt;/body&gt;</div><div class="line">&lt;/html&gt;</div></pre></td></tr></table></figure>
<h2 id="Demo"><a href="#Demo" class="headerlink" title="Demo"></a>Demo</h2><p>在线demo部署在daocloud <a href="http://gobaidu.daoapp.io/" target="_blank" rel="external">http://gobaidu.daoapp.io/</a></p>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        
  <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
    <div>请我喝杯咖啡！</div>
    <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
      <span>赏</span>
    </button>
    <div id="QR" style="display: none;">
      
        <div id="wechat" style="display: inline-block">
          <img id="wechat_qr" src="http://7xrz9n.com1.z0.glb.clouddn.com/wechatpay.png" alt="willxue WeChat Pay"/>
          <p>微信打赏</p>
        </div>
      
      
        <div id="alipay" style="display: inline-block">
          <img id="alipay_qr" src="http://7xrz9n.com1.z0.glb.clouddn.com/alipay.png" alt="willxue Alipay"/>
          <p>支付宝打赏</p>
        </div>
      
    </div>
  </div>


      
    </div>

    <div>
      
        

      
    </div>

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/go/" rel="tag"># go</a>
          
        </div>
      

      
        
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blog/golang-learn-0-20161122/" rel="next" title="go语言学习之零">
                <i class="fa fa-chevron-left"></i> go语言学习之零
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
      <div id="SOHUCS"></div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="http://willxue.ufile.ucloud.com.cn/logo.png"
               alt="willxue" />
          <p class="site-author-name" itemprop="name">willxue</p>
           
              <p class="site-description motion-element" itemprop="description">晚上少吃点？</p>
          
        </div>
        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
              <a href="/archives">
                <span class="site-state-item-count">14</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-categories">
              <a href="/categories/index.html">
                <span class="site-state-item-count">6</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-tags">
              <a href="/tags/index.html">
                <span class="site-state-item-count">10</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        
          <div class="feed-link motion-element">
            <a href="/atom.xml" rel="alternate">
              <i class="fa fa-rss"></i>
              RSS
            </a>
          </div>
        

        <div class="links-of-author motion-element">
          
        </div>

        
        
          <div class="cc-license motion-element" itemprop="license">
            <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" class="cc-opacity" target="_blank">
              <img src="/images/cc-by-nc-sa.svg" alt="Creative Commons" />
            </a>
          </div>
        

        
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#开始"><span class="nav-text">开始</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#项目结构"><span class="nav-text">项目结构</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#main-go"><span class="nav-text">main.go</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#index-html"><span class="nav-text">index.html</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Demo"><span class="nav-text">Demo</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy;  2015 - 
  <span itemprop="copyrightYear">2017</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">willxue</span>
</div>


<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Pisces
  </a>
</div>


        

        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>

  
  <script type="text/javascript" src="/lib/canvas-nest/canvas-nest.min.js"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.0"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.0"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.0"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.0"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.0"></script>



  


  




	





  





  





  




  
    <script type="text/javascript">
    (function(){
      var appid = 'cysUrBDmO';
      var conf = 'c41ca3e91546e81c9c07a9e0e35caacd';
      var width = window.innerWidth || document.documentElement.clientWidth;
      if (width < 960) {
      window.document.write('<script id="changyan_mobile_js" charset="utf-8" type="text/javascript" src="https://changyan.sohu.com/upload/mobile/wap-js/changyan_mobile.js?client_id=' + appid + '&conf=' + conf + '"><\/script>'); } else { var loadJs=function(d,a){var c=document.getElementsByTagName("head")[0]||document.head||document.documentElement;var b=document.createElement("script");b.setAttribute("type","text/javascript");b.setAttribute("charset","UTF-8");b.setAttribute("src",d);if(typeof a==="function"){if(window.attachEvent){b.onreadystatechange=function(){var e=b.readyState;if(e==="loaded"||e==="complete"){b.onreadystatechange=null;a()}}}else{b.onload=a}}c.appendChild(b)};loadJs("https://changyan.sohu.com/upload/changyan.js",function(){
        window.changyan.api.config({appid:appid,conf:conf})});
      }
    })();
    </script>
    <script type="text/javascript" src="https://assets.changyan.sohu.com/upload/plugins/plugins.count.js"></script>
  



  





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.1.js"></script>
  <script>AV.initialize("QImiFijLSOHYufsazlBVlwLg-gzGzoHsz", "AMcYaNHy9Y5OdH42k0d4uSED");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


  

  

  

</body>
</html>
